package com.bank.basic.service.impl;

import com.bank.basic.service.FileConnectService;
import com.bank.basic.service.FileService;
import com.bank.basic.util.*;
import com.bank.common.commonUtil.FileUtil;
import com.bank.model.entity.File;
import com.bank.model.entity.FileConnect;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Cejay1314
 * @version 1.0
 * @create 2023/4/5 13:33
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MapperFactory mapperFactory;
    @Autowired
    EntityFactory entityFactory;
    @Autowired
    VoFactory voFactory;
    @Autowired
    ClientFactory clientFactory;
    @Autowired
    FileConnectService fileConnectService;


    @Override
    public File queryFile(String fileName) {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", fileName);
        return mapperFactory.getFileMapper().selectOne(queryWrapper);
    }

    @Override
    public void saveFile(MultipartFile file, Long loanId) throws IOException {
        String fileName = FileUtil.storeFile(file);
        File fileData = entityFactory.getFile(fileName);
        mapperFactory.getFileMapper().insert(fileData);
        FileConnect fileConnect = entityFactory.getFileConnect(fileData.getId(), loanId);
        mapperFactory.getFileConnectMapper().insert(fileConnect);
    }

    @Override
    public void download(Long sourceId, HttpServletResponse httpServletResponse) {
        FileConnect fileConnect = fileConnectService.querySourceID(sourceId);
        File file = mapperFactory.getFileMapper().selectById(fileConnect.getFileId());
        download(file.getName(),httpServletResponse);
    }

    @Override
    public void download(String name, HttpServletResponse httpServletResponse) {
        FileUtil.downFile(name,httpServletResponse);
    }
}
